﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.MenuCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.MenuHandler
{
    public class DelMenuHandler : IRequestHandler<DelMenuCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        private readonly IMapper mapper;

        public DelMenuHandler(IBaseRepository<Menu> menuRep,IMapper mapper)
        {
            this.menuRep = menuRep;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list= await menuRep.GetModelAsync(request.MenuId);
            if (list==null)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "删除失败";
                result.Data = 0;

            }
            await GetMenuId(list);
            result.Code = APIEnum.Success;
            result.Msg = "删除成功";
            result.Data = 1;
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        public async Task GetMenuId(Menu menu)
        {
            menu.IsDeleted = true;
            await menuRep.UpdateAsync(menu);
            var children=await menuRep.GetAsync(x=>x.PId==menu.MenuId);
            foreach (var item in children) 
            {
                  await GetMenuId(item);
            }
        }
    }
}
